from django.shortcuts import render

# Create your views here.
from drf_haystack.viewsets import HaystackViewSet
from rest_framework.filters import OrderingFilter
from rest_framework.generics import ListAPIView, CreateAPIView
from rest_framework.response import Response
from rest_framework.views import APIView

from goods.models import SKU, GoodsCategory
from goods.serializers import GoodsSerializer, SKUIndexSerializer
from goods.utils import StandardResultsSetPagination


class SKUListView(ListAPIView):
    serializer_class = GoodsSerializer
    #  分页器
    pagination_class = StandardResultsSetPagination

    # 排序
    filter_backends = [OrderingFilter]
    ordering_fields = ['create_time', 'price', 'sales']

    # 重写get_queryset方法
    def get_queryset(self):
        pk = self.kwargs["pk"]
        return SKU.objects.filter(category_id=pk)


class GoodCategorieView(APIView):
    def get(self, request, pk):
        """获取三级分类并返回"""
        cat3 = GoodsCategory.objects.get(id=pk)
        cat2 = cat3.parent
        cat1 = cat2.parent

        return Response({'cat1': cat1.name,
                         'cat2': cat2.name,
                         'cat3': cat3.name,
                         })


class SKUSearchViewSet(HaystackViewSet):
    """
    SKU搜索
    """
    pagination_class = StandardResultsSetPagination

    index_models = [SKU]

    serializer_class = SKUIndexSerializer

